﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using WeifenLuo.WinFormsUI.Base;

namespace HRM
{
    public partial class FormGLAccGroup : FormBaseDataMstDtl
    {
        private DataSet mdsGLAccGroup_Header, mdsGLAccGroup_Details;
        private SqlDataAdapter mdaGLAccGrpHUpdate, mdaGLAccGrpDUpdate;
        private Ctrl_General mCtrlGeneral;
        private CurrencyManager mCurrencyManagerDetail;

        public FormGLAccGroup()
        {
            InitializeComponent();
        }

        protected override void BasicForm_Load(object sender, EventArgs e)
        {
            base.BasicForm_Load(sender, e);
        }

        protected override void BaseForm_Activated(object sender, EventArgs e)
        {
            base.BaseForm_Activated(sender, e);
        }

        protected override void BaseForm_KeyDown(object sender, KeyEventArgs e)
        {
            base.BaseForm_KeyDown(sender, e);
        }

        protected override void BasicForm_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            base.BasicForm_Closing(sender, e);
        }

        protected override void LoadMasterData()
        {
            try
            {
                btnCancel = btncancel;
                btnOk = btnok;
                lblStatus = lblstatus;
                LoadData();
                LoadDataDetails(txtGLAccGrp.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot open GL Account Group'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        #region LoadData
        private void LoadData()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                ClearDataBinding(this);
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string ls_SQL = " Select ID_GLAccGroup, GLAccGroup_Name, Note, CreatedUser, UpdatedUser, CreatedDate, UpdatedDate From HRM_GLAccGroup_Header ";

                mdsGLAccGroup_Header = mCtrlGeneral.GetSelect(ls_SQL, "HRM_GLAccGroup_Header");
                mCtrlGeneral.GetAllData(out mdaGLAccGrpHUpdate, "HRM_GLAccGroup_Header", " Order By ID_GLAccGroup ");

                if (mdsGLAccGroup_Header == null) return;
                //Binding: TextBox, Label
                txtGLAccGrp.DataBindings.Add(new Binding("Text", mdsGLAccGroup_Header.Tables[0], "ID_GLAccGroup"));
                txtGLAccGrpName.DataBindings.Add(new Binding("Text", mdsGLAccGroup_Header.Tables[0], "GLAccGroup_Name"));
                txtNote.DataBindings.Add(new Binding("Text", mdsGLAccGroup_Header.Tables[0], "Note"));

                mRowManager = (CurrencyManager)txtGLAccGrp.BindingContext[mdsGLAccGroup_Header.Tables[0]];
                // How to refresh the status of the row position?Ordinal_Number
                mRowManager.PositionChanged += new EventHandler(RowMaster_Changed);

                SetData2List(mdsGLAccGroup_Header);
                SetReadOnly(this, false);
                base.LoadMasterData();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load header data'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region LoadDataDetails
        private void LoadDataDetails(string as_IDGLAccGrp)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondition = " ID_GLAccGroup = '" + as_IDGLAccGrp + "'";

                mdsGLAccGroup_Details = mCtrlGeneral.GetDataWithCondition(out mdaGLAccGrpDUpdate, "HRM_GLAccGroup_Details", lCondition);

                if (mdsGLAccGroup_Details == null) return;

                mdbg_DetailGrid.DataSource = mdsGLAccGroup_Details;
                mdbg_DetailGrid.DataMember = "HRM_GLAccGroup_Details";

                mCurrencyManagerDetail = (CurrencyManager)mdbg_DetailGrid.BindingContext[mdsGLAccGroup_Details, "HRM_GLAccGroup_Details"];
                mCurrencyManagerDetail.PositionChanged += new EventHandler(RowMaster_Changed);

                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load details data'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region SetReadOnly
        private void SetReadOnly(Control aCtrl, bool abReadOnly)
        {
            foreach (Control lCtrl in aCtrl.Controls)
            {
                switch (lCtrl.GetType().ToString())
                {
                    case "System.Windows.Forms.TextBox":
                        ((TextBox)lCtrl).ReadOnly = !abReadOnly;
                        break;
                }
            }
        }
        #endregion

        #region Move Events
        public override void move_first()
        {
            base.move_first();
            if (GetCurrentAction() == MODES.ADD)
            {
                if (mdsGLAccGroup_Details == null) LoadDataDetails(txtGLAccGrp.Text.Trim());
                AddDetails();
            }
            else
            {
                LoadDataDetails(txtGLAccGrp.Text.Trim());
                if (GetCurrentAction() == MODES.MODIFY) ModifyDetails();
            }
        }

        public override void move_last()
        {
            base.move_last();
            if (GetCurrentAction() == MODES.ADD)
            {
                if (mdsGLAccGroup_Details == null) LoadDataDetails(txtGLAccGrp.Text.Trim());
                AddDetails();
            }
            else
            {
                LoadDataDetails(txtGLAccGrp.Text.Trim());
                if (GetCurrentAction() == MODES.MODIFY) ModifyDetails();
            }
        }

        public override void move_next()
        {
            base.move_next();
            if (GetCurrentAction() == MODES.ADD)
            {
                if (mdsGLAccGroup_Details == null) LoadDataDetails(txtGLAccGrp.Text.Trim());
                AddDetails();
            }
            else
            {
                LoadDataDetails(txtGLAccGrp.Text.Trim());
                if (GetCurrentAction() == MODES.MODIFY) ModifyDetails();
            }
        }

        public override void move_previous()
        {
            base.move_previous();
            if (GetCurrentAction() == MODES.ADD)
            {
                if (mdsGLAccGroup_Details == null) LoadDataDetails(txtGLAccGrp.Text.Trim());
                AddDetails();
            }
            else
            {
                LoadDataDetails(txtGLAccGrp.Text.Trim());
                if (GetCurrentAction() == MODES.MODIFY) ModifyDetails();
            }
        }
        #endregion

        #region add
        public override void add()
        {
            try
            {
                base.add();
                AddDetails();
                mRowManager.EndCurrentEdit();
                mRowManager.AddNew();
                SetReadOnly(this, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot add new. Error: " + ex.Message, ConstantKeys.Title);
            }
        }
        #endregion

        #region Add Details
        private void AddDetails()
        {
            if (mdsGLAccGroup_Details != null) mdsGLAccGroup_Details.Clear();
            mdbg_DetailGrid.Focus();
            mdbg_DetailGrid.AllowUserToAddRows = true;
            mdbg_DetailGrid.AllowUserToOrderColumns = false;
            mCurrencyManagerDetail.Position = mdsGLAccGroup_Details.Tables[0].Rows.Count;
        }
        #endregion

        #region modify
        public override void modify()
        {
            base.modify();
            SetReadOnly(this, true);
            txtGLAccGrp.ReadOnly = true;
            ModifyDetails();
        }
        #endregion

        #region Modify details
        private void ModifyDetails()
        {
            mdbg_DetailGrid.Focus();
            mdbg_DetailGrid.AllowUserToAddRows = false;
            mdbg_DetailGrid.AllowUserToOrderColumns = false;
            mdbg_DetailGrid.ReadOnly = false;
            mCurrencyManagerDetail.Position = mdsGLAccGroup_Details.Tables[0].Rows.Count;
        }
        #endregion

        #region cancel
        public override void cancel()
        {
            if (mdsGLAccGroup_Header == null) return;
            mRowManager.EndCurrentEdit();
            mdsGLAccGroup_Header.RejectChanges();
            base.cancel();
            CancelDetails();
            SetReadOnly(this, false);
        }
        #endregion

        #region Cancel Details
        private void CancelDetails()
        {
            if (mdsGLAccGroup_Details != null)
            {
                if (mdsGLAccGroup_Details.Tables[0].Rows.Count > 0)
                {
                    
                    mCurrencyManagerDetail.EndCurrentEdit();
                    mdsGLAccGroup_Details.RejectChanges();
                }
                else
                    mdsGLAccGroup_Details.Clear();
            }
            mdbg_DetailGrid.AllowUserToAddRows = false;
        }
        #endregion

        #region save
        public override void save()
        {
            if (!mdbg_DetailGrid.EndEdit()) return;
            mRowManager.EndCurrentEdit();
            if (mdsGLAccGroup_Header == null) return;
            if (txtGLAccGrp.Text.Trim().Equals(""))
            {
                MessageBox.Show("Cannot update'. Error: GL Account Group ID. cannot empty.", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtGLAccGrp.Focus();
                return;
            }

            DataRow dr = mdsGLAccGroup_Header.Tables[0].Rows[mRowManager.Position];
            if (dr.RowState == DataRowState.Modified)
            {
                dr["UpdatedUser"] = mMainForm.ms_UserID;
                dr["UpdatedDate"] = DateTime.Now;
            }
            else if(dr.RowState == DataRowState.Added)
            {
                dr["CreatedUser"] = mMainForm.ms_UserID;
                dr["CreatedDate"] = DateTime.Now;
            }

            string ls_ColName = "", ls_TableName = "";
            string ls_Error = mCtrlGeneral.Update(mdaGLAccGrpHUpdate, mdsGLAccGroup_Header, "HRM_GLAccGroup_Header", out ls_ColName, out ls_TableName);
            if (ls_Error == "")
            {
                mdsGLAccGroup_Header.AcceptChanges();
                if (!SaveDetails()) return;
                if (GetCurrentAction() == MODES.ADD) LoadData();
                base.save();
                SetReadOnly(this, false);
            }
            else
                MessageBox.Show("Cannot update'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        #endregion

        #region Save Details
        private bool SaveDetails()
        {
            try
            {
                if (mdsGLAccGroup_Details == null || txtGLAccGrp.Text.Equals(""))
                {
                    mdbg_DetailGrid.AllowUserToAddRows = false;
                    mdbg_DetailGrid.AllowUserToOrderColumns = false;
                    return true;
                }
                if (mdsGLAccGroup_Details.Tables[0].Rows.Count == 0)
                {
                    mdbg_DetailGrid.AllowUserToAddRows = false;
                    mdbg_DetailGrid.AllowUserToOrderColumns = false;
                    return true;
                }
                else
                {
                    DataRow ldr = mdsGLAccGroup_Details.Tables[0].Rows[0];
                    if (ldr.RowState != DataRowState.Deleted)
                    {
                        if (ldr["ID_GLAccGroup"].ToString() != "" && ldr["ID_GLAccGroup"].ToString() != txtGLAccGrp.Text)
                        {
                            mdbg_DetailGrid.AllowUserToAddRows = false;
                            mdbg_DetailGrid.AllowUserToOrderColumns = false;
                            return true;
                        }
                    }
                    else
                    {
                        mdbg_DetailGrid.AllowUserToAddRows = false;
                        mdbg_DetailGrid.AllowUserToOrderColumns = false;
                    }
                }

                mCurrencyManagerDetail.EndCurrentEdit();

                if (!mdsGLAccGroup_Details.HasChanges())
                {
                    mdbg_DetailGrid.AllowUserToAddRows = false;
                    mdbg_DetailGrid.AllowUserToOrderColumns = false;
                    return true;
                }

                DataSet ldsHasChanged = mdsGLAccGroup_Details.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    //dr["Line_No"]	= 1;
                    dr["ID_GLAccGroup"] = txtGLAccGrp.Text.Trim();
                    if (dr.RowState == DataRowState.Added)
                    {
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                        dr["CreatedDate"] = DateTime.Now;
                    }
                    else if(dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                        dr["UpdatedDate"] = DateTime.Now;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaGLAccGrpDUpdate, ldsHasChanged, "HRM_GLAccGroup_Details", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsGLAccGroup_Details.AcceptChanges();
                    LoadDataDetails(txtGLAccGrp.Text);
                    mdbg_DetailGrid.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    MessageBox.Show("Cannot update'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        #endregion

        #region delete
        public override void delete()
        {
            base.delete();
            if (!mb_AcceptDelete) return;
            if (!DeleteDetails()) return;
            DataSet ldsDelete = mdsGLAccGroup_Header;
            DataRow ldrDelete = ldsDelete.Tables[0].Rows[mRowManager.Position];
            int li_Pos = mRowManager.Position;
            ldrDelete.Delete();
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaGLAccGrpHUpdate, ldsDelete, "HRM_GLAccGroup_Header", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("Cannot delete. Error: " + lsReturnMessage, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
                mRowManager.Position = li_Pos;
                SetReadOnly(this, false);
                return;
            }
            //else
            //	DeleteTabPage();	//Delete TabPage
            base.post_delete();
            LoadDataDetails(txtGLAccGrp.Text.Trim());
            SetReadOnly(this, false);
        }
        #endregion

        #region Delete
        private bool DeleteDetails()
        {
            if (mdsGLAccGroup_Details == null) return true;
            if (mdsGLAccGroup_Details.Tables[0].Rows.Count == 0) return true;

            DataSet ldsDelete = (DataSet)mdbg_DetailGrid.DataSource;
            int i;
            for (i = 0; i < ldsDelete.Tables[0].Rows.Count; i++)
            {
                DataRow ldrDelete = ldsDelete.Tables[0].Rows[i];
                ldrDelete.Delete();
            }
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaGLAccGrpDUpdate, ldsDelete, "HRM_GLAccGroup_Details", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("Cannot delete. Error: " + lsReturnMessage, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
                return false;
            }
            return true;
        }
        #endregion

        public override void SetListChanged()
        {
            LoadDataDetails(txtGLAccGrp.Text.Trim());
        }

        private void btnok_Click(object sender, System.EventArgs e)
        {
            save();
        }

        private void btncancel_Click(object sender, System.EventArgs e)
        {
            cancel();
        }
        
    }
}
